package com.tang.common.utils.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.tang.common.exception.BusinessException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateConverter implements Converter<LocalDate> {


    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.DATE;
    }


    @Override
    public LocalDate convertToJavaData(ReadConverterContext<?> context) throws Exception {
        String format = context.getContentProperty().getField().getAnnotation(JsonFormat.class).pattern();
        try {
            return LocalDate.parse(context.getReadCellData().getStringValue(), DateTimeFormatter.ofPattern(format));
        } catch (Exception e) {
            try {
                return LocalDate.parse(context.getReadCellData().getStringValue() + "-01", DateTimeFormatter.ofPattern(format + "-dd"));
            } catch (Exception e1) {
                throw new BusinessException(500, "时间不是 yyyy-MM 格式");
            }
        }
    }


    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<LocalDate> context) throws Exception {
        String format = context.getContentProperty().getField().getAnnotation(JsonFormat.class).pattern();
        return new WriteCellData<>(context.getValue().format(DateTimeFormatter.ofPattern(format)));
    }
}
